package com.biqee.service.juhuasuan.impl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.biqee.model.JuHuaSuanItemOfPage;
import com.biqee.service.juhuasuan.ItemListParser;
import com.biqee.util.JsoupUtil;

public class ItemListParserImpl implements ItemListParser {
	private static final Logger logger = Logger.getLogger(ItemListParserImpl.class);
	
	@Override
	public List<JuHuaSuanItemOfPage> parseAllItems(String htmlString) {
		Document doc = JsoupUtil.createDocument(htmlString);

		if(doc == null) {
			logger.error("doc is null, htmlString: " + htmlString);			
			return new ArrayList<JuHuaSuanItemOfPage>();
		}
		
		return parseAllItems(doc);
	}
	
	@Override
	public int getMaxPageNumber(String htmlString) {
		Document doc = JsoupUtil.createDocument(htmlString);

		if(doc == null) {
			logger.error("doc is null, htmlString: " + htmlString );
			
			return 0;
		}
		
		return getMaxPageNumber(doc);
	}
	
	@Override
	public List<JuHuaSuanItemOfPage> parseAllItems(String filePath, String charsetName) {
		Document doc = JsoupUtil.createDocument(filePath, charsetName);

		if(doc == null) {
			logger.error("doc is null, filePath: " + filePath +
					", charsetName: " + charsetName);
			
			return new ArrayList<JuHuaSuanItemOfPage>();
		}
		
		return parseAllItems(doc);
	}
	

	@Override
	public int getMaxPageNumber(String filePath, String charsetName) {
		Document doc = JsoupUtil.createDocument(filePath, charsetName);

		if(doc == null) {
			logger.error("doc is null, filePath: " + filePath +
					", charsetName: " + charsetName);
			
			return 0;
		}
		
		return getMaxPageNumber(doc);
	}

	@Override
	public List<JuHuaSuanItemOfPage> parseAllItems(InputStream inputStream,
			String charsetName, String baseUrl) {
		Document doc = JsoupUtil.createDocument(inputStream, charsetName, baseUrl);

		if(doc == null) {
			logger.error("doc is null, charsetName: " + charsetName +
					", baseUrl: " + baseUrl);
			
			return new ArrayList<JuHuaSuanItemOfPage>();
		}
		
		return parseAllItems(doc);
	}

	@Override
	public int getMaxPageNumber(InputStream inputStream, String charsetName,
			String baseUrl) {
		Document doc = JsoupUtil.createDocument(inputStream, charsetName, baseUrl);

		if(doc == null) {
			logger.error("doc is null, charsetName: " + charsetName +
					", baseUrl: " + baseUrl);
			
			return 0;
		}
		
		return getMaxPageNumber(doc);
	}

	private List<JuHuaSuanItemOfPage> parseAllItems(Document doc) {
		List<JuHuaSuanItemOfPage> items = new ArrayList<JuHuaSuanItemOfPage>();

		try {
			Elements uls = doc.select("ul.clearfix");
			for (Element ul : uls) {
				Elements lis = ul.select("li");
				for (Element li : lis) {
					JuHuaSuanItemOfPage item = parseItem(li);
					if(item != null) {
						items.add(item);
					}
				}
			}
		} catch (Exception e) {
			logger.error("parse doc failed, cause: ", e);
		}
		
		return items;
	}
	
	/*
	 <div class="ju-pagination">
			<div class="page-bottom tp">
	        	<span class="page-start"><span><b class="icon"></b>上一页</span></span>
	        	<span class="page-cur">1</span>
			<a href="http://ju.taobao.com/tg/today_items.htm?page=2">2</a>
                	<a href="http://ju.taobao.com/tg/today_items.htm?page=3">3</a>
                	<a href="http://ju.taobao.com/tg/today_items.htm?page=4">4</a>
                	<a href="http://ju.taobao.com/tg/today_items.htm?page=5">5</a>
                	<a href="http://ju.taobao.com/tg/today_items.htm?page=6">6</a>
			<a class="page-next" href="http://ju.taobao.com/tg/today_items.htm?page=2">下一页<b class="icon"></b></a>
			</div>
		</div>
	 */
	private int getMaxPageNumber(Document doc) {		
		try {
			Element pageDivElement = doc.select("div.ju-pagination").first();
			Elements aHrefElements = pageDivElement.select("a");
			
			return aHrefElements.size();
		} catch (Exception e) {
			logger.error("getMaxPageNumber failed. doc: " + doc +
					", cause: ", e);
		}
		
		return 0;
	}
	
	private JuHuaSuanItemOfPage parseItem(Element itemElement) {
		try {
			JuHuaSuanItemOfPage item = new JuHuaSuanItemOfPage();
			
			Element divPicElement = itemElement.select("div.pic").first();
			
			Element itemUrlElement = divPicElement.select("a").first();
			String detailUrl = itemUrlElement.attr("href");
			item.setDetailUrl(detailUrl);
			
			Element h3 = itemElement.select("h3").first();
			String description = h3.text();
			item.setDescription(description);
			
			// showUrl looks like: http://ju.taobao.com/tg/home.htm?item_id=3627565336&page=1&traclelog=julistbuy" 
			String itemId = null;
			String itemToken = "item_id=";
			int idIndex = detailUrl.indexOf(itemToken);
			if(idIndex == -1) {
				throw new RuntimeException("itemId not found in url: " + detailUrl);
			}
			String itemString = detailUrl.substring(idIndex);
			int firstOtherParameterIndex = itemString.indexOf("&");
			if(firstOtherParameterIndex == -1) {
				itemId = itemString.substring(itemToken.length());
			} else {
				itemId = itemString.substring(itemToken.length(), firstOtherParameterIndex);
			}

			item.setItemId(itemId);
			
			return item;			
		} catch (Exception ex) {
			logger.error("parseItem failed. itemElement: " + itemElement, ex);
			return null;
		}
	}
	

	public static void main(String[] args) {
		String filePath = "D:\\work\\biqee\\test-pages\\taobao\\juhuasuan\\jhs-list.html";
		ItemListParserImpl parser = new ItemListParserImpl();
		List<JuHuaSuanItemOfPage> items = parser.parseAllItems(filePath, "gbk");
		
		for(JuHuaSuanItemOfPage item : items) {
			String desc = ToStringBuilder.reflectionToString(item, ToStringStyle.MULTI_LINE_STYLE);
			System.out.println(desc);
		}
	}
}
